﻿using log4net.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdverseEventReportSystem.Utils {
    /// <summary>
    /// Log4net配置设置类
    /// </summary>
    public class Log4netConfig {
        private static readonly object locker = new object();

        /// <summary>
        /// 初始化log4net配置
        /// </summary>
        /// <param name="loggerName">日志实例名</param>
        /// <param name="isWatchFile">是否监控配置文件变化</param>
        public static void SetConfig(string loggerName, bool isWatchFile) {
            string log4netUri = ConfigHelper.GetConfigString("Log4netUri");
            string fileName = WebUtils.GetMapPath(log4netUri);
            FileInfo configFile = new FileInfo(fileName);
            //为了保证只初始化一次，需要考虑线程安全
            if (!IsContainSpecifiedLogger(loggerName, log4net.LogManager.GetRepository().GetCurrentLoggers())) {
                lock (locker) {
                    if (!IsContainSpecifiedLogger(loggerName, log4net.LogManager.GetRepository().GetCurrentLoggers())) {
                        if (isWatchFile) {
                            log4net.Config.XmlConfigurator.ConfigureAndWatch(configFile);
                        } else {
                            log4net.Config.XmlConfigurator.Configure(configFile);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 返回指定的Logger是否已经配置过
        /// </summary>
        /// <param name="loggerName">指定的Logger名称</param>
        /// <param name="arrLogger">已经配置过的Logger数组</param>
        /// <returns>如果在Logger数组中找到指定的名称，则返回true，否则返回false。</returns>
        private static bool IsContainSpecifiedLogger(string loggerName, ILogger[] arrLogger) {
            foreach (ILogger logger in arrLogger) {
                if (logger.Name == loggerName) {
                    return true;
                }
            }
            return false;
        }
    }
}
